import { get } from 'lodash';

import { getStore } from '../store';
import { setVerifyCodeCountDown } from '../actions';
import AppStateUtils from './AppStateUtils';

class VerifyCountDownCorrectUtils {
  constructor() {
    this.store = getStore();
  }

  startCorrectListener() {
    console.log(`====> startCorrectListener`);
    AppStateUtils.setChangeEventCallback(this._correctVerifyCountDown);
  }

  /**
   * 修正验证码倒计时
   */
  _correctVerifyCountDown = lastTime => {
    console.log(`===> lastTime: ${lastTime}`);
    // 计算恢复前台时与上一次进入后台的时间差
    const timeOffset = Math.round((Date.now() - lastTime) / 1000);
    const state = this.store.getState();
    const active = get(
      state,
      ['common', 'verifyCodeCountDown', 'active'],
      false
    );
    let remaining = get(
      state,
      ['common', 'verifyCodeCountDown', 'remaining'],
      0
    );
    // 如果是验证码倒计时活跃中，才会进行修正
    if (!active) {
      return;
    }
    // 修正剩余时间，当其小于 0 时设置为0
    remaining = remaining - timeOffset;
    remaining = remaining > 0 ? remaining : 0;
    this.store.dispatch(
      setVerifyCodeCountDown({
        correct: true, // 代表时间被修正过
        active: remaining > 0, // 当剩余时间 > 0 时，设置为活跃
        remaining: remaining,
      })
    );
  };
}

VerifyCountDownCorrectUtils = new VerifyCountDownCorrectUtils();

export default VerifyCountDownCorrectUtils;
